package com.liming.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.liming.model.User;
import com.liming.utils.DataSourceUtils;

public class Userdao {
	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
	//根据用户名 密码查找用户 
	public User findUser(String username,String password){
		List<User> user = null;
		String sql = "Select * from user where username = ? and password = ?";
		try {
			user = qr.query(sql, new BeanListHandler<>(User.class),username,password);
			if (user.size()==0||user==null) {
				return null;
			}

			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return user.get(0);
	}
	//添加用户
	public int  addUser(User user){
		String sql ="insert into user(username,password,userphone,useremail) values (?,?,?,?)";
		Object[] params={user.getUsername(),user.getPassword(),user.getUserphone(),user.getUseremail()};
		int a=0;
		try {
			a=qr.update(sql,params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return a;
	}
	//通过用户名查找用户
	public boolean findUser(String username){
		List<User> user = null;
		String sql = "Select * from user where username = ? ";
		try {
			user = qr.query(sql, new BeanListHandler<>(User.class),username);
			if (user.size()==0||user==null) {
				return false;
			}	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}
	//拿到用户的商店id
	public int getShopId(String username) {
		
		String sql="select shopid from user where username=?";
		int shopid=-1;
		try {
			shopid=(int) qr.query(sql,new ScalarHandler(),username);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(shopid);
		return shopid;
	}
}
